<?php
namespace logic\admin\wechat;
use library\tencent\wechat\admin_wechat\WechatMpService;
use library\tencent\wechat\common\WechatMP;
use model\WechatMenu;
use think\Db;

/**
 * Created by lsx.
 * User: lsx
 * Date: 2017/4/18
 * Time: 10:21
 */
class LWechatMenu
{

    public function index_data($param){
        $where=array();
        if (!empty($keywords)) {
            $where['name'] = array('like', "%{$keywords}%"); //查询条件
        }
        $total = db('wechat_menu')->where($where)->count(); //记录总数
        $page_size =$param['limit']; //获取分页数
        $start = $param['offset']; //获取开始的记录数
        //获取排序字段------------------------------------------------------------开始

        $sort_name = $param['ordinal'];
        $sort_desc = $param['order'];
        //$order[$sort_name] = $sort_desc;

        if (!empty($sort_name)) {
            $sort[$sort_name] = $sort_desc;
        } else {
            $sort['type'] = 'asc'; //默认排序
        }
        //获取排序字段------------------------------------------------------------结束
        $rows = db('wechat_menu')
            ->limit($start, $page_size)
            ->order($sort)
            ->select();
        $array=array(
            'total'=>$total,
            'rows'=>$rows
        );

        return $array;
    }

    public function insert_data($param){
        $param['type']=2;
        $param['status']=1;
        $param['data_source']=json_encode($param['data']);
//        var_dump($param['data']);die();
        $param['data']=base64_encode(self::iserializer(array_values($this->array_values($param['data']))));

//        var_dump($param);die();
        $model=new WechatMenu();
        $res=$model->save($param);
        if($res){
            return array(
                'success'=>true,
                'message'=>'添加成功'
            );
        }else{
            return array(
                'success'=>false,
                'message'=>'添加失败'
            );
        }

    }

    public function array_values($data){
        $new_data=array_values($data);
//        var_dump($new_data);die();
        foreach ($new_data as &$item) {

            if(key_exists('sub_button',$item) && $item['sub_button']){
                $item['sub_button']=array_values($item['sub_button']);
            }
        }
        return $new_data;
    }

    public function edit_data($id){
        $model=new WechatMenu();
        $data=$model->where(['id'=>$id])->find();
//        $data['menu_data']=self::iunserializer(base64_decode($data['data']));
        $data['menu_data']=json_decode($data['data_source'],true);
        return $data;
    }

    public function update_data($id,$param){
        $param['type']=2;
        $param['status']=1;
        $param['data_source']=json_encode($param['data']);
//        var_dump($param['data']);die();
        $param['data']=base64_encode(self::iserializer(array_values($this->array_values($param['data']))));
        $model=new WechatMenu();
        $res=$model->where(['id'=>$id])->update($param);
        if($res){
            return array(
                'success'=>true,
                'message'=>'修改成功'
            );
        }else{
            return array(
                'success'=>false,
                'message'=>'修改失败'
            );
        }
    }

    public function delete_data($id){
        $model=new WechatMenu();
        $res=$model->where(['id'=>$id])->delete();
        if($res){
            return array(
                'success'=>true,
                'message'=>'删除成功'
            );
        }else{
            return array(
                'success'=>false,
                'message'=>'删除失败'
            );
        }
    }

    public function push_to_online_data($id){
        $model=new WechatMenu();
        $data_01['type']=1;
        $data_01['create_time']=time();

        $data=$model->where(['id'=>$id])->find();
        $accessToken=WechatMpService::getAccessToken();
        $post = self::iunserializer(base64_decode($data['data']));
        $res=WechatMP::menuCreate($accessToken,$post);
        if($res->getCode()==0 and $res->getMessage()=="ok"){
            //判断是否有已推送的菜单，有则更改已推送为未推送
            $al=$model->where(['type'=>1])->find();
            if($al){
                $model->where(['type'=>1])->setField('type',2);
            }
            //复制 一条数据，更改状态为【已推送】
            $data_01=$model->where(['id'=>$id])->find();
            $data_01=$model->where(['id'=>$id])->find();
            $data_arr=$data_01->getData();
            array_shift($data_arr);
            $data_arr['type']=1;
            $data_arr['create_time']=time();
            $model->save($data_arr);
            return array(
                'success'=>true,
                'message'=>'推送成功'
            );
        }else{
            return array(
                'success'=>false,
                'message'=>'推送失败'
            );
        }
    }

    public function iserializer($value) {
        return serialize($value);
    }
    public function iunserializer($value) {
        if (empty($value)) {
            return '';
        }
        if (!self::is_serialized($value)) {
            return $value;
        }
        $result = unserialize($value);
        if ($result === false) {
            $temp = preg_replace_callback('!s:(\d+):"(.*?)";!s', function ($matchs){
                return 's:'.strlen($matchs[2]).':"'.$matchs[2].'";';
            }, $value);
            return unserialize($temp);
        }
        return $result;
    }
    public function is_serialized($data, $strict = true) {
        if (!is_string($data)) {
            return false;
        }
        $data = trim($data);
        if ('N;' == $data) {
            return true;
        }
        if (strlen($data) < 4) {
            return false;
        }
        if (':' !== $data[1]) {
            return false;
        }
        if ($strict) {
            $lastc = substr($data, -1);
            if (';' !== $lastc && '}' !== $lastc) {
                return false;
            }
        } else {
            $semicolon = strpos($data, ';');
            $brace = strpos($data, '}');
            if (false === $semicolon && false === $brace)
                return false;
            if (false !== $semicolon && $semicolon < 3)
                return false;
            if (false !== $brace && $brace < 4)
                return false;
        }
        $token = $data[0];
        switch ($token) {
            case 's' :
                if ($strict) {
                    if ('"' !== substr($data, -2, 1)) {
                        return false;
                    }
                } elseif (false === strpos($data, '"')) {
                    return false;
                }
            case 'a' :
            case 'O' :
                return (bool)preg_match("/^{$token}:[0-9]+:/s", $data);
            case 'b' :
            case 'i' :
            case 'd' :
                $end = $strict ? '$' : '';
                return (bool)preg_match("/^{$token}:[0-9.E-]+;$end/", $data);
        }
        return false;
    }

}